import { defineConfig } from "vite"
import vue from "@vitejs/plugin-vue"
import { fileURLToPath, URL } from 'node:url'
import { viteStaticCopy } from 'vite-plugin-static-copy'
import fs from 'fs'
import path from 'path'

// 自定义插件：在构建完成后删除目标文件
const deleteTargetFile = () => ({
  name: 'delete-target-file',
  closeBundle: () => {
    const targetFile = path.resolve(__dirname, 'dist/Chrome.zip')
    if (fs.existsSync(targetFile)) {
      fs.unlinkSync(targetFile)
      console.log('dist/Chrome.zip 文件已删除')
    }
  }
})

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    viteStaticCopy({
      targets: [
        {
          src: 'public/Chrome.zip',
          dest: 'assets'
        }
      ]
    }),
    deleteTargetFile()
  ],
  resolve: {
    alias: {
      "@": fileURLToPath(new URL("./src", import.meta.url)),
    },
  },
  server: {
    open: true,
    port: 5273,
    proxy: {
      "/proxy": {
        target: "http://47.99.181.165:9091", // 目标服务器
        changeOrigin: true, // 改变请求源，避免跨域问题
        rewrite: (path: string) => path.replace(/^\/proxy/, ""), // 重写 URL 去掉 `/api` 前缀
      },
    },
  },
  build: {
    assetsDir: 'assets',
    outDir: 'dist',
    rollupOptions: {
      output: {
        manualChunks: undefined
      }
    }
  }
})
